package com.zhinong.controller.admin;

import com.zhinong.annotation.SelectCache;
import com.zhinong.constant.JwtClaimsConstant;
import com.zhinong.dto.EmployeeDTO;
import com.zhinong.dto.EmployeeLoginDTO;
import com.zhinong.dto.EmployeePageQueryDTO;
import com.zhinong.entity.Employee;
import com.zhinong.properties.JwtProperties;
import com.zhinong.result.PageResult;
import com.zhinong.result.Result;
import com.zhinong.service.EmployeeService;
import com.zhinong.utils.JwtUtil;
import com.zhinong.vo.EmployeeLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 员工管理
 */
@RestController
@RequestMapping("/admin/employee")
@Slf4j
@Api(tags = "员工相关接口")
public class EmployeeController {



    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 登录
     *
     * @param employeeLoginDTO
     * @return
     */



    @PostMapping("/login")
    @ApiOperation(value = "员工登录")
    public Result<EmployeeLoginVO> login(@RequestBody EmployeeLoginDTO employeeLoginDTO) {
        log.info("员工登录：{}", employeeLoginDTO);

        Employee employee = employeeService.login(employeeLoginDTO);

        //登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, employee.getId());
        String token = JwtUtil.createJWT(
                jwtProperties.getAdminSecretKey(),
                jwtProperties.getAdminTtl(),
                claims);

        EmployeeLoginVO employeeLoginVO = new EmployeeLoginVO();

// 手动设置属性
        employeeLoginVO.setId(employee.getId());
        employeeLoginVO.setUserName(employee.getUsername());
        employeeLoginVO.setName(employee.getName());
        employeeLoginVO.setToken(token);
        return Result.success(employeeLoginVO);
    }

/*        EmployeeLoginVO employeeLoginVO = EmployeeLoginVO.builder()
                .id(employee.getId())
                .userName(employee.getUsername())
                .name(employee.getName())
                .token(token)
                .build();

         return Result.success(employeeLoginVO);

    /**
     * 退出
     *
     * @return
     */
    @PostMapping("/logout")
    @ApiOperation(value = "员工退出")
    public Result<String> logout() {
        return Result.success();
    }

    @PostMapping
    @ApiOperation("新增员工")
    public Result save(@RequestBody EmployeeDTO employeeDTO){
        log.info("新增员工:{}",employeeDTO);
        employeeService.save(employeeDTO);
        return Result.success(employeeDTO);
    }


    @SelectCache(name = "employeePageQuery")
    @GetMapping("/page")
    @ApiOperation("员工分页查询")
    //员工分页查询
    public Result<PageResult> page(EmployeePageQueryDTO employeePageQueryDTO){
        // 构建查询key
//        String selectKey = "PageQuery" + employeePageQueryDTO.getPage()+employeePageQueryDTO.getPageSize();
//        PageResult pageResult = (PageResult) redisTemplate.opsForValue().get(selectKey);
//        if(pageResult!=null){
//            log.info("缓存命中");
//            return Result.success(pageResult);
//        }
//        //查询
//        log.info("员工分页查询,参数为:{}",employeePageQueryDTO);
        PageResult pageResult = employeeService.pageQuery(employeePageQueryDTO);
//        redisTemplate.opsForValue().set(selectKey,pageResult);
        return Result.success(pageResult);
    }

    @PostMapping("/status/{status}")
    @ApiOperation("启用禁用员工账号")
    public Result starOrStop(@PathVariable Integer status,Long id){
        log.info("启用禁用员工账号:{},{}",status,id);
        employeeService.starOrStop(status,id);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询员工")
    public Result<Employee> getByID(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        return Result.success(employee);
    }



    @PutMapping("/{id}")
    @ApiOperation("编辑员工信息")
    public Result update(@RequestBody EmployeeDTO employeeDTO){
        log.info("编辑员工:#{}",employeeDTO);

        employeeService.update(employeeDTO);
//        String deleteKey = "Page"+"*";
//        Set keys = redisTemplate.keys(deleteKey);
//        redisTemplate.delete(keys);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("员工删除")
    public Result delete(@PathVariable Long id){
        log.info("删除员工:{}",id);
//        employeeService.deleteById(id);
        try{
            rabbitTemplate.convertAndSend("employeedead.direct","employeedead.success",id, message-> {
                message.getMessageProperties().setDelayLong(10000L);
                return message;
            });
            }catch (Exception e){
            log.info("消息发送失败");
        };
        return Result.success();
    }
}

